<template>
  <div style="width: 100%; height: 100%">
    <guangbopanelCard
     :headerFlag="true"
    >
      <template #header>
        <div style="display: flex; align-items: center;width: 100%;">
          <div style="width: 15%; display: flex; align-items: center">
            <span class="searchColor themfontColor">呼叫字冠</span>
            <el-input v-model="state.searchData.headNumber"
              placeholder="请输入"
              style="width: 60%;margin-left: 15px"
              clearable></el-input>
          </div>
                    <div style="width: 20%; display: flex; align-items: center">
            <span class="searchColor themfontColor">业务类型</span>
            <el-select
              v-model="state.searchData.type"
              style=" margin-left: 15px"
              clearable
            >
               <el-option label="本局业务" value="0"></el-option>
              <el-option label="出局业务" value="1"></el-option>
            </el-select>
          </div>
          <div>
            <el-button
              type="primary"
              @click="queryFn"
              >查询</el-button
            >
            <el-button @click="resetFn">重置</el-button>
          </div>
        </div>
      </template>
      <template #article>
        <guangbovxeTB
        ref="guangbovxeTB"
          title="号码分析"
          :tableheads_show="state.tableheads_show"
          :listUrl="state.listUrl"
          :caozuoList="state.caozuoList"
          @addFn="addFn"
          @delAllFn="delAllFn"
          @edit="editFn"
          @bofang="bofangFn"
          @shanchu="delFn"
        ></guangbovxeTB>
      </template>
    </guangbopanelCard>
    <!-- 新增 -->
    <el-dialog v-model="state.addFlag" width="30%" :before-close="handleClose">
      <template #title>
        <span class="themfontColor">{{ state.addTitle }}</span>
      </template>
      <div style="width: 100%; display: flex; justify-content: center">
        <el-form ref="formRef" :model="state.formData" :rules="state.formDataRules" label-width="120px">
          <el-form-item label="呼叫字冠" prop="headNumber">
           <el-input v-model="state.formData.headNumber" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="业务类型" prop="type">
            <el-select v-model="state.formData.type" placeholder="请选择">
              <el-option label="本局业务" value="0"></el-option>
              <el-option label="出局业务" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="state.formData.type==1" label="路由选择码" prop="routerChoice">
           <el-input v-model.number="state.formData.routerChoice" placeholder="请输入" oninput ="value=value.replace(/[^0-9.]/g,'')"></el-input>
          </el-form-item>
                    <el-form-item label="最小号长" prop="minLength">
           <el-input v-model.number="state.formData.minLength" placeholder="请输入" oninput ="value=value.replace(/[^0-9.]/g,'')"></el-input>
          </el-form-item>
                    <el-form-item label="最大号长" prop="maxLength">
           <el-input v-model.number="state.formData.maxLength" placeholder="请输入" oninput ="value=value.replace(/[^0-9.]/g,'')"></el-input>
          </el-form-item>
          <!-- <el-form-item label="选择文件">
            <el-upload
              ref="uploadRef"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :on-change="handleFileChange"
              class="upload-demo"
              accept=".mp3"
              action="#"
              :auto-upload="true"
              drag
              :limit="1"
              :multiple="false"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="upload__text">
                <div>点击或将文件拖拽到这里上传</div>
                <div>支持mp3格式，最大10MB</div>
              </div>
            </el-upload>
          </el-form-item> -->
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveAddFn"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 播放 -->
    <el-dialog
      v-model="state.bofangFlag"
      width="22%"
      :before-close="bofanghandleClose"
    >
      <template #title>
        <span class="themfontColor">播放</span>
      </template>
      <div style="text-align: center">
        <el-form
          ref="bofangRef"
          :model="state.form"
          :rules="state.rules"
          label-width="100px"
        >
          <el-form-item label="音乐名称：">
            <span class="themfontColor">{{ state.detailData.MusicName }}</span>
          </el-form-item>
          <el-form-item label="播放次数：" prop="num">
            <el-input
              v-model="state.form.num"
              type="Number"
              :min="1"
              :max="100"
              style="width: 240px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="广播号码：" prop="phone">
            <el-select v-model="state.form.phone" style="width: 240px" multiple>
              <el-option
                v-for="item in state.telephoneData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <!-- <audio src="@/assets/guangboimg/鸟叫.mp3" controls autoplay></audio> -->
        <el-button @click="startFn" type="primary">开启</el-button>
        <el-button @click="endFn">关闭</el-button>
        <!-- <audio :src="state.detailData.FilePath" controls autoplay></audio> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue-demi";
import axios from "@/utils/request";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { table_headers } from "@/assets/table_headers/table_headers";
import usepagesStore from "@/store/modules/pages";
const userStore = usepagesStore();
const props = defineProps({});
const emit = defineEmits([""]);
const { proxy } = getCurrentInstance();
let state = reactive({
  searchData: {},
  addTitle:'新增',
  formData:{},
  formDataRules: {
    headNumber: [
      {
        required: true,
        message: "请输入呼叫源码",
        trigger: "blur",
      },
    ],
     type: [
      {
        required: true,
        message: "请输入业务类型",
        trigger: "blur",
      },
    ],
    routerChoice: [
      {
        required: true,
        message: "请输入路由选择码",
        trigger: "blur",
      },
    ],
    minLength: [
      {
        required: true,
        message: "请输入最小号长",
        trigger: "blur",
      },
    ],
     maxLength: [
      {
        required: true,
        message: "请输入最大号长",
        trigger: "blur",
      },
    ],
  },
  form: { num: 1, phone: [] },
  rules: {
    num: [
      {
        required: true,
        message: "请输入播放次数",
        trigger: "blur",
      },
    ],
    phone: [
      {
        required: true,
        message: "请选择广播号码",
        trigger: "change",
      },
    ],
  },
  addFlag: false,
  bofangFlag: false,
  caozuoList: [
    // {
    //   caozuoType: "bofang",
    //   label: "播放",
    //   type: "text",
    // },
        {
      caozuoType: "edit",
      label: "编辑",
      type: "text",
    },
    {
      caozuoType: "shanchu",
      label: "删除",
      type: "text",
    },
  ],
  selectData: [],
  tabledata: [],
  tableheads_show: computed(() => table_headers.t_sip_router),
  detailData: {},
  telephoneData: [],
  uploadData: {},
  uploadUrl: "",
  fileType: ["mp3"],
  listUrl:'/sip/config/router/list',
  addUrl:'/sip/config/router/add',
  editUrl:'/sip/config/router/edit',
  delUrl:'/sip/config/router/',
  detailUrl:'/sip/config/router/',
});
//新增弹层
const addFn = () => {
  //新增
  state.addTitle = '新增';
  state.addFlag = true;
};
const editFn = (row) => {
  //编辑
  console.log(row, "row");
  state.addTitle = '编辑';
  state.addFlag = true;
  state.formData = row;
  state.formData.type=(state.formData.type+'');
};
const handleClose = () => {
  //关闭
  state.addFlag = false;
  state.formData = {};
  proxy.$refs["formRef"].resetFields();
};
const saveAddFn = () => {
  //保存
  let url = state.addUrl;
  if(state.addTitle=='新增'){
    url = state.addUrl;
  }else{
    url = state.editUrl;
  }
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      axios
       .post(url, state.formData)
       .then((res) => {
          if (res.code == 200) {
            // state.addFlag = false;
            ElMessage.success(res.msg);
proxy.$refs["guangbovxeTB"].getList();
            handleClose()
          }else{
            ElMessage.error(res.msg);
          }
        })
       .catch((err) => {
        ElMessage.error(res.msg);
        });
    }
  });
};
const bofangFn = (row) => {
  //播放
  state.detailData = row;
  state.bofangFlag = true;
};
const bofanghandleClose = (row) => {
  //播放关闭
  state.bofangFlag = false;
};
function startFn() {
  //开启
  proxy.$refs["bofangRef"].validate((isOk) => {
    if (isOk) {
      axios
        .post("/Service/GetWebApiControlBroadcast", {
          type: 0, //0 开始播放 1关闭播放
          TerminalNOs: state.form.phone, //广播号码集合
          MusicIDs: [state.detailData.MusicID], //音乐ID集合，开始播放必填
          frequency: state.form.num, //播放次数
        })
        .then((res) => {
          if (res.Result == true) {
            ElMessage.success(res.Msg);
            state.bofangFlag = false;
          } else {
            ElMessage.error(res.Msg);
          }
        });
    }
  });
}
function endFn() {
  //关闭
  proxy.$refs["bofangRef"].validate((isOk) => {
    if (isOk) {
      axios
        .post("/Service/GetWebApiControlBroadcast", {
          type: 1, //0 开始播放 1关闭播放
          TerminalNOs: state.form.phone, //广播号码集合
          MusicIDs: [state.detailData.MusicID], //音乐ID集合，开始播放必填
          frequency: state.form.num, //播放次数
        })
        .then((res) => {
          ElMessage.success("关闭成功");
          state.bofangFlag = false;
        });
    }
  });
}
const delAllFn = () => {
 if (userStore.records.length == 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  } else {
    let str = [];
    userStore.records.forEach((item) => {
      str.push(item.id);
    });
    ElMessageBox.confirm("确认删除?", "提示", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        axios.delete(state.delUrl + str.join(",")).then((res) => {
          ElMessage.success("删除成功");
          userStore.records = [];
          proxy.$refs["guangbovxeTB"].getList();
        });
      })
      .catch(() => {});
  }
}
const delFn = (row) => {
  //删除
  state.detailData = row;
  ElMessageBox.confirm("确认删除?", '提示', {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .delete(state.delUrl+row.id)
        .then((res) => {
          ElMessage.success("删除成功");
proxy.$refs["guangbovxeTB"].getList();
        });
    })
    .catch(() => {});
};
function handleFileChange(file) {}

function uploadSuccess(item) {}
async function beforeUpload(file) {
  console.log(file, "file");

  state.uploadData = file;
  if (file.type != "" || file.type != null || file.type != undefined) {
    //截取文件的后缀，判断文件类型
    const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    file.name.substring(0, file.name.lastIndexOf(".")); //截取文件前缀
    //计算文件的大小
    const isLt5M = file.size / 1024 / 1024 < 10; //这里做文件大小限制
    //const isLt5M = file.size / 1024 < 500; //500kb
    //如果大于50M
    if (!isLt5M) {
      ElMessage.error("上传文件过大!");
      return false;
    } else {
      try {
        const compressedFile = await compressAudio(file);
        let pattern = /base64,(.*)/; // 使用正则表达式匹配指定字符后面的内容
        let result = compressedFile.match(pattern)[1]; // 提取匹配结果的第一个捕获组
        state.uploadUrl = result;
        saveAddFn();
        // 这里可以将compressedFile发送到服务器
      } catch (error) {
        console.error("压缩失败:", error);
      }
    }

    //如果文件类型不在允许上传的范围内
    if (state.fileType.includes(FileExt)) {
      return true;
    } else {
      proxy.$message.error("请上传mp3格式文件!");
      return false;
    }
  }
}
function compressAudio(file) {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((resolve, reject) => {
    reader.onload = (event) => {
      const compressedBase64 = event.target.result; // 获取Base64字符串
      // 这里可以添加压缩逻辑，例如使用lamejs或其他库压缩mp3
      // 压缩后的音频通常会更小，可以用来减少上传数据量
      // 压缩后的操作代码...
      resolve(compressedBase64);
    };
    reader.onerror = (error) => {
      reject(error);
    };
  });
}
const queryFn = () => {
  //查询
let obj = {};
     obj.headNumber = state.searchData.headNumber;
   obj.type = state.searchData.type;
     proxy.$refs["guangbovxeTB"].state.searchData = obj;
  proxy.$refs["guangbovxeTB"].getList();
};
const resetFn = () => {
  //重置
let obj = {};
  state.searchData = {};
  proxy.$refs["guangbovxeTB"].state.searchData = obj;
  proxy.$refs["guangbovxeTB"].getList();
};
onMounted(() => {
  queryFn();
});
</script>